package org.example.SolutionNew001;

import java.util.*;

public class Hash02 {
    public static void main(String[] args) {
        Hash02 hash = new Hash02();
        String[] strs=new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        System.out.println(hash.groupAnagrams(strs).toString());
    }

    public List<List<String>> groupAnagrams1(String[] strs) {
        List<List<String>> res = new ArrayList<List<String>>();
        String[] str = new String[strs.length];
        for(int i=0;i<strs.length;i++){
            str[i]=sortString(strs[i]);
        }
        List<String> first=new ArrayList<>();
        first.add(strs[0]);
        res.add(first);
        Map<String,Integer> map=new HashMap<>();
        map.put(str[0],0);
        for(int i=1;i<strs.length;i++){
            if(map.containsKey(str[i])){
                res.get(map.get(str[i])).add(strs[i]);
            }else{
                map.put(str[i],map.size());
                List<String> tmp=new ArrayList<>();
                tmp.add(strs[i]);
                res.add(tmp);
            }
        }
        return res;
    }

    public String sortString(String str) {
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        return Arrays.toString(chars);
    }

    public List<List<String>> groupAnagrams2(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for(String s:strs){
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            List<String> list=map.getOrDefault(key,new ArrayList<>());
            list.add(s);
            map.put(key,list);
        }
        return new ArrayList<List<String>>(map.values());
    }

    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> map=new HashMap<>();
        for(String s:strs){
            int[] count=new int[26];
            for(char c:s.toCharArray()){
                count[c-'a']++;
            }
            StringBuilder sb=new StringBuilder();
            for(int i=0;i<26;i++){
                if(count[i]>=1){
                    sb.append((char)(i+'a'));
                    sb.append(count[i]);
                }
            }
            String key=sb.toString();
            List<String> tmp=map.getOrDefault(key,new ArrayList<>());
            tmp.add(s);
            map.put(key,tmp);
        }
        return new ArrayList<List<String>>(map.values());
    }
}
